package com.crealth.thread;


import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import com.alibaba.fastjson.JSONObject;
import com.crealth.db.ConsumerDb;
import com.crealth.handler.ResponseMsgQueue;
import com.crealth.model.ConsumerInfoModel;
import com.crealth.msg.NetMessageData;
import com.crealth.utils.Utils;


public class ImportConsumerThread extends Thread {
	private static Logger errorLog = Logger.getLogger("error_log");
	
	private String importFileName;
	private int userID;
	private JSONObject fieldMapJson;
	
	public ImportConsumerThread(String fileName, int userID) {
		importFileName = fileName;
		this.userID = userID;
		fieldMapJson = null;
	}
	
	public void setFieldMapJson(JSONObject setJson) {
		fieldMapJson = setJson;
	}
	
	@Override
	public void run() {
		importMobi();
	}
	
	private void importMobi() {
		Sheet sheet;
        Workbook book;
        Cell curCell;       
        try {
        	String strFileName = "./uploadData/" + importFileName;
        	InputStream is = new FileInputStream(strFileName);
            book = WorkbookFactory.create(is);
            sheet = book.getSheetAt(0);
            Row rowObj = sheet.getRow(0);
            int colSum = rowObj.getLastCellNum();
            int rowSum = sheet.getLastRowNum();
            int nCol = 0;           
            int nRow = 0;           
        	String strValue = "";
        	List<String> titlels = new ArrayList<String>();
            for (nCol = 0; nCol < colSum; ++nCol ) {
            	curCell = rowObj.getCell(nCol);
            	if (curCell == null) {
            		break;
            	}
            	strValue = curCell.toString().trim();
            	if (strValue.isEmpty()) {
            		break;                		
            	}
            	titlels.add(strValue);
            }
            sendProgressMsg(0, rowSum-1);
            int nInportNum = 0;
            for (nRow = 1; nRow < rowSum; ++nRow) {
            	ConsumerInfoModel consumerInfo = new ConsumerInfoModel();
            	int findFieldNum = 0;
            	rowObj = sheet.getRow(nRow);
                for (nCol = 0; nCol < colSum; ++nCol ) {
                	if (nCol >= titlels.size()) {
                		break;
                	}
                	String title = titlels.get(nCol);
                	curCell = rowObj.getCell(nCol);
                	if (curCell == null) {
                		continue;
                	}
                	strValue = curCell.toString().trim();
                	consumerInfo.setUserID(userID);
                	if (fieldMapJson == null) {  // 数据模板导入
	                	if (title.equals("产品")) {                		
	                	} else if (title.equals("姓名")) {
	                		consumerInfo.setName(strValue);
	                	} else if (title.equals("电话号码") || title.equals("电话")) {
	                		if (strValue.startsWith("1.") || strValue.indexOf('E') > 0) {
	    	            		strValue = ImportClienteleDetailThread.doublePhoneNumToString(strValue);
	    	            	}
	                		if (strValue.length() != 11) {
	                			continue;
	                		}
	                		consumerInfo.setPhoneNum1(strValue);
	                	} else if (title.equals("客户类型")) {
	                		consumerInfo.setCliType(strValue);
	                	} else if (title.equals("备注")) {
	                		consumerInfo.setMemo(strValue);
	                	} else if (title.equals("跟进时间")) {
	                		java.util.Date date = curCell.getDateCellValue();
	                        if (date != null) {
	                            Timestamp tm = new Timestamp(date.getTime());
								consumerInfo.setLastfollowupTm(tm);
	                		}
	                	} else if (title.equals("开发时间")) {
	                		java.util.Date date = curCell.getDateCellValue();
	                        if (date != null) {                         
	                            Timestamp tm = new Timestamp(date.getTime());
								consumerInfo.setDevTime(tm);
	                		}
	                	} else if (title.equals("跟进记录")) {
	                		consumerInfo.setFollowupInfo(strValue);
	                	}
                	} else {  //  字段映射   导入数据
                		if (fieldMapJson.containsKey("产品") && title.equals(fieldMapJson.get("产品")) ) {                		
	                	} else if (fieldMapJson.containsKey("姓名") && title.equals(fieldMapJson.get("姓名")) ) {
	                		consumerInfo.setName(strValue);
	                		findFieldNum++;
	                	} else if (fieldMapJson.containsKey("电话号码") && title.equals(fieldMapJson.get("电话号码")) || 
	                			fieldMapJson.containsKey("电话") && title.equals(fieldMapJson.get("电话")) ) {
	                		if (strValue.length() != 11) {
	                			break;
	                		}
	                		consumerInfo.setPhoneNum1(strValue);
	                		findFieldNum++;
	                	} else if (fieldMapJson.containsKey("客户类型") && title.equals(fieldMapJson.get("客户类型")) ) {
	                		consumerInfo.setCliType(strValue);
	                		findFieldNum++;
	                	} else if (fieldMapJson.containsKey("备注") && title.equals(fieldMapJson.get("备注")) ) {
	                		consumerInfo.setMemo(strValue);
	                		findFieldNum++;
	                	} else if (fieldMapJson.containsKey("跟进时间") && title.equals(fieldMapJson.get("跟进时间")) ) {
	                		java.util.Date date = curCell.getDateCellValue();
	                        if (date != null) {                           
	                            Timestamp tm = new Timestamp(date.getTime());
								consumerInfo.setLastfollowupTm(tm);
	                		}
	                		findFieldNum++;
	                	} else if (fieldMapJson.containsKey("开发时间") && title.equals(fieldMapJson.get("开发时间")) ) {
	                		java.util.Date date = curCell.getDateCellValue();
	                        if (date != null) {                          
	                            Timestamp tm = new Timestamp(date.getTime());
								consumerInfo.setDevTime(tm);
	                		}
	                		findFieldNum++;
	                	} else if (fieldMapJson.containsKey("跟进记录") && title.equals(fieldMapJson.get("跟进记录")) ) {
	                		consumerInfo.setFollowupInfo(strValue);
	                		findFieldNum++;
	                	}
                		
                		if (findFieldNum >= fieldMapJson.size()) {
                			break;
                		}
                	}                	
                }
                String cliName = consumerInfo.getName();
        		String phoneNum1 = consumerInfo.getPhoneNum1();
        		if (phoneNum1 == null || phoneNum1.length() != 11) {
        			continue;
        		}
        		Integer existID = ConsumerDb.selectConsumerInfoByNameAndPhone(userID, cliName, phoneNum1);
        		if (existID != null) {
        			continue;
        		}
                ConsumerDb.insertConsumerInfoObj(consumerInfo);
                nInportNum++;
                if (nInportNum % 10 == 0) {
                	sendProgressMsg(nInportNum, rowSum-1);
                }
            }
            sendProgressMsg(nInportNum, rowSum-1);
                
            book.close();
            Utils.deleteFile(strFileName);
        } catch(Exception e) {
        	errorLog.error("", e);
        }
	}
	
	private void sendProgressMsg(int curNum, int sumNum) {
		NetMessageData sendMsg = new NetMessageData();
		sendMsg.setMsgCmd(NetMessageData.Net_Import_Consumer);
		JSONObject resJson = new JSONObject();
		
		resJson.put("resCode", 0);
		resJson.put("curNum", curNum);
		resJson.put("sumNum", sumNum);
        sendMsg.setMsgBody(resJson.toJSONString());
        ResponseMsgQueue.addMsgToQueue(NetMessageData.Net_Import_Consumer, 
        		userID, sendMsg);
	
	}
	
	
}
